<template>
  <div class="medication-container">
    <div class="vertical-warning">广告位招租，联系XXX</div>
    <h3><i class="fas fa-stethoscope"></i> 基本信息</h3>



    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button
          v-if="!editMode"
          type="primary"
          @click="editMode = true"
          icon="el-icon-edit"
          class="action-btn"
      >编辑
      </el-button>
      <el-button
          v-if="!editMode"
          type="success"
          @click="addNewHistory"
          icon="el-icon-plus"
          class="action-btn"
      >新增
      </el-button>
      <el-button
          v-if="!editMode"
          type="warning"
          @click="toggleSort"
          icon="el-icon-sort"
          class="action-btn"
      >{{ sortButtonText }}
      </el-button>

      <template v-else>
        <el-button
            type="success"
            @click="saveChanges"
            icon="el-icon-check"
            class="confirm-btn"
        >保存
        </el-button>
        <el-button
            type="danger"
            @click="cancelEdit"
            icon="el-icon-close"
            class="cancel-btn"
        >取消
        </el-button>
      </template>
    </div>

    <div class="medication-list">
      <div
          class="medication-card"
          :class="{ 'sample-data': isSampleData }"
          v-for="(report, index) in checkupReports"
          :key="report.recordId || index"
      >
        <div class="medication-header">
          <span class="detail-label"><i class="far fa-id-card"></i> ID:{{ report.recordId }}</span>
          <div class="checkup-status" v-if="!editMode">
            <i class="far fa-calendar-alt"></i> {{ report.recordDate }}
          </div>
        </div>




          <div class="detail-row">
            <span class="detail-label"><i class="fas fa-chart-line"></i> 身体指标:</span>
            <div v-if="!editMode" class="health-indicators">
              <div>身高: {{ report.height }}m</div>
              <div>体重: {{ report.weight }}kg</div>
              <div>BMI: {{ report.bmi }}</div>
              <div>血压: {{ report.bloodPressure }}</div>
              <div>血糖: {{ report.bloodSugar }}</div>
              <div>心率: {{ report.heartRate }}</div>
            </div>
            <div v-else class="health-inputs">
              <div>身高:<el-input-number v-model="report.height" :precision="2" :step="0.01" placeholder="身高(cm)"/>m</div>
              <div>体重:<el-input-number v-model="report.weight" :precision="2" :step="0.01" placeholder="体重(kg)"/>kg</div>
              <div>BMI:<el-input-number v-model="report.bmi" :precision="2" :step="0.01" placeholder="体重(kg)"/></div>
              <div>血压(格式：收缩/舒张）:<el-input v-model="report.bloodPressure" placeholder="血压"/></div>
              <div>血糖:<el-input v-model="report.bloodSugar" placeholder="血糖"/></div>
              <div>心率:<el-input v-model="report.heartRate" placeholder="心率"/></div>
            </div>
          </div>

        <!-- 删除按钮放在每张卡片内 -->
        <div class="card-actions" v-if="editMode">
          <el-button
              type="danger"
              size="small"
              @click="deleteHandler(index)"
              icon="el-icon-delete"
          >删除
          </el-button>
        </div>

      </div>




      </div>


    <!-- 分页控件 -->
    <div class="pagination-controls">
      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="totalRecords"
          :page-sizes="[1,2,4,8,10, 20, 30, 50]"
          layout=" sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>

    <!-- 弹出对话框 -->
    <div class="popup-container" :class="{ 'show-popup': showAddDialog }">
      <div class="popup-backdrop" @click="showAddDialog = false"></div>
      <div class="popup-dialog" :class="{ 'scale-in': showAddDialog }">
        <div class="popup-header">
          <div class="popup-title">
            <i class="fas fa-plus-circle header-icon"></i>
            <h3>新增健康记录</h3>
          </div>
          <button class="close-button" @click="showAddDialog = false">
            <i class="el-icon-close"></i>
          </button>
        </div>
        <el-form :model="currentReport" label-width="100px">
          <el-form-item label="身高(m)" prop="height">
            <el-input-number v-model="currentReport.height" :precision="2" :step="0.01" />
          </el-form-item>
          <el-form-item label="体重(kg)" prop="weight">
            <el-input-number v-model="currentReport.weight" :precision="2" :step="0.01" />
          </el-form-item>
          <el-form-item label="bmi" prop="weight">
            <el-input-number v-model="currentReport.bmi" :precision="2" :step="0.01" />
          </el-form-item>

          <el-form-item label="血压(格式：收缩/舒张）" prop="bloodPressure">
            <el-input v-model="currentReport.bloodPressure" placeholder="如：120/80mmHg" />
          </el-form-item>
          <el-form-item label="血糖" prop="bloodSugar">
            <el-input v-model="currentReport.bloodSugar" placeholder="如：5.6mmol/L" />
          </el-form-item>
          <el-form-item label="心率" prop="heartRate">
            <el-input v-model="currentReport.heartRate" placeholder="如：75次/分" />
          </el-form-item>

          <el-form-item label="备注" prop="remarks">
            <el-input
                v-model="currentReport.remarks"
                type="textarea"
                :rows="2"
                placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>

        <div class="popup-footer">
          <el-button
              class="custom-cancel-btn"
              @click="showAddDialog = false"
          >取消
          </el-button>
          <el-button
              type="primary"
              class="custom-confirm-btn"
              @click="saveNewCheckup"
          >保存记录
          </el-button>
        </div>

      </div>

    </div>
    <div class="total-records-notice">
      <el-icon>
        <info-filled/>
      </el-icon>
      您共有{{ totalRecords }}份健康记录
    </div>
  </div>
</template>


<script setup>
import {reactive, ref, onMounted, nextTick,computed} from 'vue';
import {
  createHealthRecord,
  deleteHealthRecord,
  getBasicInfo,
  updateHealthRecord
} from '@/api/profile.js';
import {ElButton, ElMessage, ElMessageBox, ElPagination} from 'element-plus';
import {InfoFilled} from "@element-plus/icons-vue";
// 添加日志导入
import { postLog } from '@/api/log';

const checkupReports = ref([]);
const currentReport = reactive({
  recordType: '健康指标',
  height: 0,
  weight: 0,
  bmi: 0,
  bloodPressure: '',
  bloodSugar: '',
  heartRate: '',
  remarks: ''
});

// 共用状态
const editMode = ref(false);
const isSortedAscending = ref(true);
const sortButtonText = computed(() => isSortedAscending.value ? '按日期排序 ↑' : '按日期排序 ↓');
const showAddDialog = ref(false);
const currentPage = ref(1);
const pageSize = ref(8);
const totalRecords = ref(0);
const userInfo = ref(null);
const originalMedications = ref([]);

const storedUser = localStorage.getItem('currentUser');
userInfo.value = storedUser ? JSON.parse(storedUser) : null;
// 获取体检报告数据
const loadCheckupData = async () => {
  try {

    const res = await getBasicInfo(userInfo.value?.id, {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    });
    isSortedAscending.value = !isSortedAscending.value;
    res.data.data.sort((a, b) => {
      return isSortedAscending.value
          ? a.recordDate.localeCompare(b.recordDate)
          : b.recordDate.localeCompare(a.recordDate);
    });
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    checkupReports.value = res.data.data.slice(startIndex, endIndex);
    console.log(123,checkupReports.value)
    originalMedications.value = JSON.parse(JSON.stringify(res.data.data));

    totalRecords.value = res.data.data.length;
  } catch (error) {
    ElMessage.error('获取数据失败');
  }
};

// 完善分页处理
const toggleSort = () => {
  loadCheckupData();
};

const handlePageChange = (newPage) => {
  isSortedAscending.value = !isSortedAscending.value;
  currentPage.value = newPage;
  loadCheckupData();
};

// 初始化加载数据
onMounted(() => {
  loadCheckupData();
});

const addNewHistory = () => {
  console.log('新增按钮点击事件触发');
  Object.assign(currentReport, {
    recordId: null,
    recordDate: new Date().toISOString().split('T')[0],
    recordType: '健康指标',
    height: 0,
    weight: 0,
    bmi: 0,
    bloodPressure: '',
    bloodSugar: '',
    heartRate: '',
    remarks: ''
  });

  // 触发对话框显示并添加动画类
  nextTick(() => {
    showAddDialog.value = true;
  });
};

// 删除记录
const deleteHandler = async (index) => {
  try {
    await ElMessageBox.confirm('确定删除该一份记录吗？');
    const report = checkupReports.value[index];
    if (report.recordId) {
      await deleteHealthRecord(report.recordId);
    }
    checkupReports.value.splice(index, 1);
    ElMessage.success('删除成功');
    if (checkupReports.value.length === 0 && currentPage.value > 1) {
      currentPage.value--;
      await loadCheckupData();
    }
    
    // 删除操作日志记录
    if (userInfo.value && report.recordId) {
      await postLog({
        id: userInfo.value.id,
        role: userInfo.value.role,
        username: userInfo.value.username,
        ip: userInfo.value.ip || '192.66.55.4', // 若 IP 不存在则设为空字符串
        loginTime: userInfo.value.loginTime || new Date().toISOString(), // 若 loginTime 不存在则设为当前时间
        recordType: '健康指标',
        action: '删除',
        recordId: report.recordId,
        logTime: new Date().toISOString() // 添加 logTime 属性
      });
    }
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('删除失败：' + error.message);
  }
};
const cancelEdit = () => {
  editMode.value = false;
  checkupReports.value = JSON.parse(JSON.stringify(originalMedications.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)));
};
// 保存修改
const saveChanges = async () => { 
  try { 
    const promises = checkupReports.value.map(async (currentReport) => { 
      await updateHealthRecord({ 
        recordId: currentReport.recordId, 
        recordDate: currentReport.recordDate, 
        recordType: '健康指标', 
        detail: `${currentReport.height}|${currentReport.weight}|${currentReport.bmi}|${currentReport.bloodPressure}|${currentReport.bloodSugar}|${currentReport.heartRate}|${currentReport.remarks}|`  
      }); 
    }); 
    await Promise.all(promises); 
    ElMessage.success('保存成功'); 
    editMode.value = false; 
    await loadCheckupData(); 
    
    // 保存操作日志记录 
    if (userInfo.value) { 
      const logPromises = checkupReports.value.map(async (report) => { 
        if (report.recordId) { 
          await postLog({ 
            id: userInfo.value.id, 
            role: userInfo.value.role, 
            username: userInfo.value.username, 
            ip: userInfo.value.ip || '192.66.55.4', 
            loginTime: userInfo.value.loginTime || new Date().toISOString(), // 若 loginTime 不存在则设为当前时间
            recordType: '健康指标', 
            action: '修改',
            recordId: report.recordId, 
            logTime: new Date().toISOString() 
          }); 
        } 
      }); 
      await Promise.all(logPromises); 
    } 
  } catch (error) { 
    ElMessage.error('保存失败'); 
  } 
};

const handleSizeChange = (val) =>{
  currentPage.value=1;
  pageSize.value = val;
  loadCheckupData();
}

// 新增记录
const saveNewCheckup = async () => { 
  try { 
    const response = await createHealthRecord(userInfo.value?.id, { 
      ...currentReport, 
      detail: `${currentReport.height}|${currentReport.weight}|${currentReport.bmi}|${currentReport.bloodPressure}|${currentReport.bloodSugar}|${currentReport.heartRate}|${currentReport.remarks}|`  
    }); 
    showAddDialog.value = false;
    await loadCheckupData();
    ElMessage.success('新增成功');
    
    // 新增操作日志记录 
    if (userInfo.value ) {
      await postLog({ 
        id: userInfo.value.id, 
        role: userInfo.value.role, 
        username: userInfo.value.username, 
        ip: userInfo.value.ip || '192.66.55.4', 
        loginTime: userInfo.value.loginTime || new Date().toISOString(), // 若 loginTime 不存在则设为当前时间
        recordType: '健康指标', 
        action: '增加',
        recordId: response.data?.data, 
        logTime: new Date().toISOString() 
      }); 
    } 
  } catch (error) { 
    ElMessage.error('新增失败');
  } 
}; 
</script>
<style scoped>
@import "@/assets/css/new.css";
</style>